package cn.snmp.mutual.uk.stack;

public class BitsHelper {
    private static final String version_id = "@(#)$Id: BitsHelper.java,v 3.1 2006/03/23 15:09:48 birgit Exp $ Copyright Westhawk Ltd";

    public static void setFlagged(final AsnOctets oct, final int index, final boolean toset) throws IllegalArgumentException {
        if (index < 0) {
            throw new IllegalArgumentException("Illegal value index (" + index + "). Shoud be greater than 0.");
        }
        final int byteNo = index / 8;
        final int bitNo = index % 8;
        final int len = oct.value.length;
        if (byteNo >= len) {
            final int newLen = byteNo + 1;
            final byte[] newValue = new byte[newLen];
            System.arraycopy(oct.value, 0, newValue, 0, len);
            oct.value = newValue;
        }
        if (toset) {
            final byte mask = (byte) (128 >>> bitNo);
            oct.value[byteNo] |= mask;
        } else {
            final byte mask = (byte) (127 >>> bitNo);
            oct.value[byteNo] &= mask;
        }
    }

    public static boolean isFlagged(final AsnOctets oct, final int index) throws IllegalArgumentException {
        boolean isFlagged = false;
        if (index < 0) {
            throw new IllegalArgumentException("Illegal value index (" + index + "). Shoud be greater than 0.");
        }
        final int byteNo = index / 8;
        final int bitNo = index % 8;
        final int len = oct.value.length;
        if (byteNo < len) {
            final byte res = (byte) (oct.value[byteNo] << bitNo);
            isFlagged = (res < 0);
        }
        return isFlagged;
    }
}
